//
//  SFNetworkManager+Extension.swift
//  SFWeiboPro
//
//  Created by happy on 2017/9/12.
//  Copyright © 2017年 happy. All rights reserved.
//

import Foundation


// MARK: 获取微博数据
extension SFNetworkManager {
    
    //获取微博信息
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, complition: @escaping (_ statuses: [[String: AnyObject]]?, _ isSuccess: Bool) -> ()) {
        
        let homeUrl = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parameters = ["since_id": "\(since_id)", "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        
        tokenRequest(URLString: homeUrl, parameters: parameters as [String : AnyObject]) { (json, isSuccess) in
            
//            print(json ?? "数据为空")
            
            let result = json?["statuses"] as? [[String: AnyObject]]
            
            complition(result, isSuccess)
        }
        
    }
    
    func unreadCount() {
        
//        let urlString = "https://api.weibo.com/2/statuses/"
        
        
    }
    
}

// MARK: OAuth授权相关
extension SFNetworkManager {
    
    func loadAccessToken(code: String, completion:@escaping (_ isSuccess: Bool) -> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id": SFAppKey,
                          "client_secret": SFAppSecret,
                          "grant_type": "authorization_code",
                          "code": code,
                          "redirect_uri": SFRedirectURL]
        
        request(method: .POST, URLString: urlString, parameters: parameters as [String : AnyObject]) { (json, isSuccess) in
            
            print(json ?? "")
            
            self.userAccount.yy_modelSet(with: (json as? [String: AnyObject]) ?? [:])
            
            print(self.userAccount)
            
            self.loadUserInfo(completion: { (dict) in
                
                self.userAccount.yy_modelSet(with: dict)
                
                //保存当前用户信息
                self.userAccount.saveAccount()
                
                print(self.userAccount)
                
                completion(isSuccess)
            })
            
        }
        
    }
    
}

// MARK: 获取用户信息
extension SFNetworkManager {
    
    func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject]) -> ()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let param = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: param as [String : AnyObject]) { (dict, isSuccess) in
            print(dict ?? [:])
            
            completion((dict as? [String : AnyObject]) ?? [:])
        }
        
    }
    
}
